package com.dogkr.server.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dogkr.common.FileDirEnum;
import com.dogkr.common.FileUtils;
import com.dogkr.server.entity.UserPet;
import com.dogkr.server.mapper.UserPetMapper;
import com.sean.common.service.BaseService;
import com.sean.common.utils.StringUtils;

@Service
public class UserPetService extends BaseService {

	@Autowired
	private UserPetMapper userPetMapper;

	public List<UserPet> selectUserPetByUserKey(Long userId) {
		return userPetMapper.selectUserPetByUserKey(userId);
	}

	public UserPet selectByPrimaryKey(Long id) {
		return userPetMapper.selectByPrimaryKey(id);
	}

	public int insert(UserPet record) {
		if (StringUtils.isNotBlank(record.getPetPhotoPath())) {
			try {
				FileUtils.removeUploadFile(record.getPetPhotoPath(),
						FileDirEnum.PET);
			} catch (IOException e) {
				log.error("宠物头像保存失败：" + record.getPetPhotoPath(), e);
				record.setPetPhotoPath(null);
			}
		}
		record.setCreateDate(new Date());
		record.setLastModifydate(record.getCreateDate());
		return userPetMapper.insert(record);
	}

	public int updateByPrimaryKeySelectiveByUser(UserPet record) {
		UserPet oldPet = userPetMapper.selectByPrimaryKey(record.getId());
		if (oldPet.getUserId().longValue() != record.getUserId())
			return 0;
		if (StringUtils.isNotBlank(record.getPetPhotoPath())) {
			if (!oldPet.getPetPhotoPath().equals(record.getPetPhotoPath())) {
				try {
					FileUtils.removeUploadFile(record.getPetPhotoPath(),
							FileDirEnum.PET);
					if (StringUtils.isNotBlank(oldPet.getPetPhotoPath())) {
						FileUtils.deleteUploadFile(oldPet.getPetPhotoPath(),
								FileDirEnum.PET);
					}
				} catch (IOException e) {
					log.error("宠物头像更新失败：" + record.getPetPhotoPath(), e);
					record.setPetPhotoPath(null);
				}
			}
		}
		record.setLastModifydate(record.getCreateDate());
		return userPetMapper.updateByPrimaryKeySelectiveWithUser(record);
	}
}
